<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记忆组列表</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="groups-page">
        <div class="header">
            <div class="sort-tabs">
                <span class="tab active" data-sort="asc">时间正序</span>
                <span class="tab" data-sort="desc">时间倒序</span>
            </div>
            <button class="create-btn" onclick="createGroup()">创建</button>
        </div>
        
        <div class="groups-container" id="groupsContainer">
            <!-- 记忆组卡片将在这里动态生成 -->
        </div>
        
        <!-- 删除确认对话框 -->
        <div class="delete-modal" id="deleteModal">
            <div class="modal-overlay" onclick="closeDeleteModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>确认删除</h3>
                    <button class="close-btn" onclick="closeDeleteModal()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="warning-icon">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
                            <line x1="12" y1="9" x2="12" y2="13"></line>
                            <line x1="12" y1="17" x2="12.01" y2="17"></line>
                        </svg>
                    </div>
                    <p class="warning-text">您确定要删除组 "<span id="deleteGroupName"></span>" 吗？</p>
                    <p class="warning-detail">此操作将永久删除该组及其所有记忆内容，无法恢复！</p>
                </div>
                <div class="modal-footer">
                    <button class="modal-btn cancel-btn" onclick="closeDeleteModal()">取消</button>
                    <button class="modal-btn confirm-delete-btn" onclick="confirmDeleteGroup()">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="js/utils.js"></script>
    <script src="js/db.js"></script>
    <script src="js/app.js"></script>
    <script>
        let currentSort = 'asc';
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async function() {
            await initDatabase();
            loadGroups();
        });

        // 加载记忆组列表
        async function loadGroups() {
            const groups = await db.getAllGroups();
            const container = document.getElementById('groupsContainer');
            
            if (groups.length === 0) {
                container.innerHTML = '<div class="empty-state">暂无记忆组，点击"创建"开始</div>';
                return;
            }

            // 按时间排序
            groups.sort((a, b) => {
                return currentSort === 'asc' 
                    ? new Date(a.createTime) - new Date(b.createTime)
                    : new Date(b.createTime) - new Date(a.createTime);
            });

            container.innerHTML = groups.map(group => `
                <div class="group-card" data-group-id="${group.id}">
                    <div class="group-icon" style="background-color: ${group.color}"></div>
                    <div class="group-info" onclick="enterGroup(${group.id})">
                        <div class="group-name">${group.name}</div>
                        <div class="group-date">创建时间: ${formatDate(group.createTime)}</div>
                    </div>
                    <div class="group-actions">
                        <button class="delete-group-btn" onclick="deleteGroup(${group.id}, '${group.name}')" title="删除组">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <polyline points="3,6 5,6 21,6"></polyline>
                                <path d="m19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2"></path>
                                <line x1="10" y1="11" x2="10" y2="17"></line>
                                <line x1="14" y1="11" x2="14" y2="17"></line>
                            </svg>
                        </button>
                    </div>
                </div>
            `).join('');
        }

        // 创建新组
        async function createGroup() {
            const groupName = prompt('请输入组名:', `第${await getNextGroupNumber()}组`);
            if (!groupName) return;

            const colors = ['#87CEEB', '#FFB6C1', '#98FB98', '#F0E68C', '#DDA0DD'];
            const randomColor = colors[Math.floor(Math.random() * colors.length)];

            const group = {
                name: groupName,
                color: randomColor,
                createTime: new Date().toISOString(),
                memoryStartTime: null // 记忆开始时间，添加第一条记忆时设置
            };

            const groupId = await db.addGroup(group);
            loadGroups();
        }

        // 进入记忆组
        function enterGroup(groupId) {
            window.location.href = `daily.html?groupId=${groupId}`;
        }

        // 获取下一个组号
        async function getNextGroupNumber() {
            const groups = await db.getAllGroups();
            return groups.length + 1;
        }

        // 删除组相关变量
        let groupToDelete = null;

        // 删除组
        function deleteGroup(groupId, groupName) {
            // 阻止事件冒泡，避免触发进入组
            event.stopPropagation();
            
            groupToDelete = groupId;
            document.getElementById('deleteGroupName').textContent = groupName;
            document.getElementById('deleteModal').style.display = 'flex';
        }

        // 确认删除组
        async function confirmDeleteGroup() {
            if (!groupToDelete) return;

            try {
                await db.deleteGroup(groupToDelete);
                showMessage('组删除成功', 'success');
                closeDeleteModal();
                loadGroups(); // 重新加载组列表
            } catch (error) {
                console.error('删除组失败:', error);
                showMessage('删除组失败: ' + error.message, 'error');
            }
        }

        // 关闭删除确认对话框
        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
            groupToDelete = null;
        }

        // 排序切换
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('tab')) {
                document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
                e.target.classList.add('active');
                currentSort = e.target.dataset.sort;
                loadGroups();
            }
        });
    </script>
</body>
</html>
